/*
 * Copyright(c)  2022 厦门外里科技有限公司 All rights reserved.
 *
 * https://www.wailikeji.com
 *
 * 版权所有，侵权必究！
 */

import Request from './request'
import apiList from './api'
import store from '@/common/store/index.js'

/**
 * 请求之前拦截器
 * @param request
 * @param api
 */
function addRequestInterceptor(request, api) {
	request.interceptor.request((config, cancel) => {
		let tokenFlag = store.getters.loginFlag;
		if (api.auth && !tokenFlag) {
			console.log('暂未登录,已阻止此次API请求~');
			store.commit('OUT_LOGIN');
			throw ('暂未登录,已阻止此次API请求~');
		}
		if (tokenFlag || store.state.user.tokenInfo) {
			//tokenInfo.access_token即为登录token
			config.header.token = store.state.user.tokenInfo;
			console.log("有token",config.header.token)
		}
		return config
	});
}

/**
 * 请求之后拦截器
 * @param request
 */
function addResponseInterceptor(request) {
	request.interceptor.response((response) => {
		console.log("↓↓↓↓↓：" + response.config.method + ":" + response.config.url, response.data)
		if (response.data.code === 401) { // 服务端返回的状态码不等于200，则reject()
			//401代表token失效
			store.commit('OUT_LOGIN');
		}

		if (response.data.code != 200) { // 服务端返回的状态码不等于200，则reject()
			uni.showToast({
				title: response.data.msg || '请求出错,稍后重试',
				icon: 'none',
				duration: 2000,
				mask: true
			});
		}


		// if (response.config.custom.verification) { // 演示自定义参数的作用
		//   return response.data
		// }
		return response
	}, (response) => { // 预留可以日志上报
		return response
	})
}

/**
 * 从api.js中获取对应的请求配置
 * @param url
 * @returns
 */
function getApiObj(url) {
	let apiArray = url.split(".");
	let api = apiList;
	apiArray.forEach(v => {
		api = api[v];
	});
	return api;
}


export default {
	api(url, data = {}) {
		return this.apiAll(url, null, null, data)
	},
	apiPath(url, path) {
		return this.apiAll(url, path, null, null)
	},
	apiParams(url, params) {
		return this.apiAll(url, null, params, null)
	},
	apiAll(url, path, params = {}, data = {}) {
		const request = new Request();
		let api = getApiObj(url);
		let tempUrl = api.url;
		if (path) {
			console.log("有path:" + path)
			tempUrl = tempUrl + path
		}
		addRequestInterceptor(request, api);
		addResponseInterceptor(request);
		let logTempUrl = tempUrl
		if (params) {
			logTempUrl = logTempUrl + "?" + Request.addQueryString(params)
		}
		console.log("↑↑↑↑↑：" + api.method + ":" + logTempUrl, data)
		return request.request({
			url: tempUrl,
			params,
			data,
			method: api.method
		})
	}

}
